﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Worktool.CODE_Chris.DataSourceHelpers;
using Worktool.CODE_Chris.SQL_DATA;
using Zen.Barcode;

namespace Worktool
{
    public partial class Commissioning : Form
    {
        List<string> listeVenue = new List<string> { };
        List<string> listeSerials = new List<string> { };
        List<string> listeSerialPositionen = new List<string> { };
        String pkInstalledPrinters;
        PrintDocument label;
        PrintDocument palettenzettel;
        int indexPosition = -1;
        int indexSerial = -1;
        private string labelSerialNumber = "";
        private string labelManufacturer = "";
        private string labelModel = "";
        private string labelPosition = "";
        private string labelVenue = "";
        private string labelJLM = "";
        private string labelTa1 = "";
        private string labelTa2 = "";
        private string labelTa3 = "";
        private string labelFittingNr = "";
        bool print = true;
        bool booking = true;

        private Boolean isInit = true;
        private SQL sql;
        private CommissioningHelper helper;

        public Commissioning()
        {
            InitializeComponent();
            this.Text = "Commissioning: " + Login.currentDBName; 
            init();
        }

        private void init()
        {
            sql = new SQL();
            helper = new CommissioningHelper(dataGridView1, dataGridView2, dataGridView3, dataGridView4, this);

            fillTablesInit();

            fillElementsInit();

            initFilterSettings();

            isInit = false;
        }

        #region Init
        private void fillElementsInit()
        {
            try
            {
                //Combobox mit Venues füllen
                String[,] areas = sql.receiveSQL("SELECT ID, Venue FROM STAMMDATEN_areas");
                comboBox1.Items.Clear();
                comboBox1.DropDownHeight = 500;

                for (int a = 0; a < areas.GetLength(1); a++)
                {
                    comboBox1.Items.Add(areas[1, a]);
                    listeVenue.Add(areas[1,a]);
                }
                comboBox1.Refresh();
                comboBox1.Text = "";

                // Drucker in das Auswahlfeld eintragen
                comboBox3.Items.Clear();
                comboBox4.Items.Clear();

                for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
                {
                    pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
                    comboBox3.Items.Add(pkInstalledPrinters);
                    comboBox4.Items.Add(pkInstalledPrinters);
                }
                for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
                {
                    if (Login.labelPrinterName == PrinterSettings.InstalledPrinters[i])
                    {
                        comboBox3.Text = Login.labelPrinterName;
                        comboBox4.Text = Login.labelPrinterName;
                    }
                }

                //Aktuelle Packstücknummer holen
                String[,] packstueck = sql.receiveSQL("SELECT ID, letztesPackstueck FROM tbl_systemData");
                if (packstueck.GetLength(1) > 0)
                {
                    textBox3.Text = packstueck[1,0];
                    button12.Text = textBox3.Text;
                }

                // Seriennummernliste füllen
                for (int i = 0; i < dataGridView1.RowCount; i++)
                {
                    listeSerials.Add(dataGridView1.Rows[i].Cells["serialNumber"].Value.ToString());
                }

            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler beim Füllen der Fertigungsauftrag Combo-Boxen. Stacktrace:\r\n\r\n" + e.StackTrace, "Fehler");
            }
        }

        private void fillTablesInit()
        {
            try
            {
                helper.getData1();
                helper.getData2();
                helper.getData3();
                //helper.getData4();
            }
            catch (Exception e)
            {

            }
        }

        private void initFilterSettings()
        {
            //Bulk
            if (helper.getTable2() != null) helper.getTable2().DefaultView.RowFilter = string.Format("isBulk = 1");

            //Material in Venue
            if (helper.getTable3() != null) helper.getTable3().DefaultView.RowFilter = string.Format("Venue LIKE ''");
        }

        private void Commissioning_Load(object sender, EventArgs e)
        {
            typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView1, new object[] { true });
            typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView2, new object[] { true });
            typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView3, new object[] { true });
            typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView4, new object[] { true });
        }
        #endregion

        #region Seriennummern prüfen und Buchung vornehmen
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            string suchModel = "";
            string suchManufacturer = "";

            // Enter Taste gedrückt und Textbox nicht leer  ?
            if (e.KeyCode == Keys.Enter && textBox1.Text != "")
            {
                // Ist die Seriennummer vielleicht schon auf eine Position gebucht ?
                #region gebucht
                if (listeSerialPositionen.Contains(textBox1.Text)) // Liste aller in dem Venue vorhandenen Seriennummern durchsuchen
                {
                    // Den richtigen Eintrag im MatDetail suchen
                    for (int i = 0; i < dataGridView3.RowCount; i++)
                    {
                        if (dataGridView3.Rows[i].Cells["Seriennummer"].Value.ToString() == textBox1.Text)
                        {
                            indexPosition = i; // Die Zeile in der die Seriennummer gefunden wurde
                            if (dataGridView3.Rows[indexPosition].Cells["Packstück Nr."].Value.ToString() != "") // Ist diese Seriennummer schon einmal auf ein Packstück gebucht worden ?
                            {
                                DialogResult dialogresult = MessageBox.Show("Vorsicht! Diese Seriennummer wurde schon auf eine Palette gebucht. Trotzdem fortfahren?", "Buchungsfehler", MessageBoxButtons.YesNo);
                                if (dialogresult == DialogResult.Yes)
                                {
                                    if (booking)
                                    {
                                        dataGridView3.Rows[indexPosition].Cells["Packstück Nr."].Value = Convert.ToInt32(textBox3.Text);
                                        helper.setColumnNr(-1);
                                        helper.gridView3_CellEndEdit(null, null);
                                    }
                                }
                                else
                                {
                                }
                            }
                            else // Wurde noch nicht auf ein Packstück gebucht
                            {
                                if (booking)
                                {
                                    dataGridView3.Rows[indexPosition].Cells["Packstück Nr."].Value = Convert.ToInt32(textBox3.Text);
                                    helper.setColumnNr(-1);
                                    helper.gridView3_CellEndEdit(null, null);
                                    //vw_eng_MaterialDetailTableAdapter.updateMaterialExtended(dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value.ToString(), Convert.ToInt32(dataGridView3.Rows[indexPosition].Cells["IDMaterialExtended"].Value));
                                }
                            }
                            break;
                        }
                    }
                    labelSerialNumber = dataGridView3.Rows[indexPosition].Cells["Seriennummer"].Value.ToString();
                    labelManufacturer = dataGridView3.Rows[indexPosition].Cells["Manufacturer"].Value.ToString();
                    labelModel = dataGridView3.Rows[indexPosition].Cells["Model"].Value.ToString();
                    labelPosition = dataGridView3.Rows[indexPosition].Cells["Positions_ID"].Value.ToString();
                    labelVenue = dataGridView3.Rows[indexPosition].Cells["Venue"].Value.ToString();
                    labelJLM = dataGridView3.Rows[indexPosition].Cells["JLM"].Value.ToString();
                    labelTa1 = dataGridView3.Rows[indexPosition].Cells["Technische_Ausprägung_1"].Value.ToString();
                    labelTa2 = dataGridView3.Rows[indexPosition].Cells["Technische_Ausprägung_2"].Value.ToString();
                    labelTa3 = dataGridView3.Rows[indexPosition].Cells["Technische_Ausprägung_3"].Value.ToString();
                    
                    label = new PrintDocument();
                    PaperSize pS = new PaperSize("Custom Size", 620, 350);
                    label.DefaultPageSettings.PaperSize = pS;
                    label.PrinterSettings.PrinterName = comboBox3.Text;
                    label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                    label.PrintPage += new PrintPageEventHandler(label_PrintPage);

                    if (print && comboBox3.Text != "")
                    {
                        label.Print();
                        label.Print();
                    }
                    // Druckstrings sicherheitshalber wieder zurück setzen
                    labelSerialNumber = "";
                    labelManufacturer = "";
                    labelModel = "";
                    labelPosition = "";
                    labelVenue = "";
                    labelJLM = "";
                    labelTa1 = "";
                    labelTa2 = "";
                    labelTa3 = "";

                    dataGridView4.Rows.Add();
                    dataGridView4.Rows[dataGridView4.RowCount-1].Cells["Time"].Value = DateTime.Now.ToShortTimeString();
                    dataGridView4.Rows[dataGridView4.RowCount-1].Cells["Event"].Value = "Already booked Serial " + textBox1.Text + " confirmed and printed";
                    isInit = true;
                    textBox1.Text = "";
                    isInit = false;
                }
                #endregion gebucht
                // Ist die Seriennummer in den Seriennummern ?
                #region vorhanden
                else if (listeSerials.Contains(textBox1.Text))
                {
                    // Den richtigen Eintrag in den Seriennummern suchen
                    for (int i = 0; i < dataGridView1.RowCount; i++)
                    {
                        if (dataGridView1.Rows[i].Cells["serialNumber"].Value.ToString() == textBox1.Text)
                        {
                            indexSerial = i;
                        }
                    }
                    // Den korrespondierenden Eintrag im Material suchen
                    suchManufacturer = dataGridView1.Rows[indexSerial].Cells["Manufacturer"].Value.ToString();
                    suchModel = dataGridView1.Rows[indexSerial].Cells["Model"].Value.ToString();
                    for (int i = 0; i < dataGridView3.RowCount; i++)
                    {
                        if (dataGridView3.Rows[i].Cells["Manufacturer"].Value.ToString() == suchManufacturer && dataGridView3.Rows[i].Cells["Model"].Value.ToString() == suchModel && dataGridView3.Rows[i].Cells["Seriennummer"].Value.ToString() == "")
                        {
                            indexPosition = i;
                        }
                    }
                    // Vielleicht schon vergeben ?
                    if (indexPosition == -1)
                    {
                        dataGridView4.Rows.Add();
                        dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Time"].Value = DateTime.Now.ToShortTimeString();
                        dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Event"].Value = "Serial " + textBox1.Text + " is already booked in this Venue ";
                        textBox1.Text = "";
                    }
                    else 
                    {
                        // Jetzt die Zuweisung
                        // erst die Seriennummer
                        dataGridView3.Rows[indexPosition].Cells["Seriennummer"].Value = dataGridView1.Rows[indexSerial].Cells["serialNumber"].Value.ToString();
                        
                        // Packstücknummer schreiben, wenn nicht schon vergeben
                        if (booking)
                        {
                            if (dataGridView3.Rows[indexPosition].Cells["Packstück Nr."].Value.ToString() != "")
                            {
                                // Schon vergeben
                                DialogResult dialogresult = MessageBox.Show("Vorsicht! Diese Seriennummer wurde schon auf eine Palette gebucht. Trotzdem fortfahren?", "Buchungsfehler", MessageBoxButtons.YesNo);
                                if (dialogresult == DialogResult.Yes)
                                {
                                    dataGridView3.Rows[indexPosition].Cells["Packstück Nr."].Value = Convert.ToInt32(textBox3.Text);
                                    helper.setColumnNr(-1);
                                    helper.gridView3_CellEndEdit(null, null);
                                }
                                else
                                {
                                }
                            }
                            else // noch nicht vergeben
                            {
                                dataGridView3.Rows[indexPosition].Cells["Packstück Nr."].Value = Convert.ToInt32(textBox3.Text);
                                helper.setColumnNr(-1);
                                helper.gridView3_CellEndEdit(null, null);
                            }
                        }

                        // Zugehöriges Label ausdrucken
                        labelSerialNumber = dataGridView3.Rows[indexPosition].Cells["Seriennummer"].Value.ToString();
                        labelManufacturer = dataGridView3.Rows[indexPosition].Cells["Manufacturer"].Value.ToString();
                        labelModel = dataGridView3.Rows[indexPosition].Cells["Model"].Value.ToString();
                        labelPosition = dataGridView3.Rows[indexPosition].Cells["Positions_ID"].Value.ToString();
                        labelVenue = dataGridView3.Rows[indexPosition].Cells["Venue"].Value.ToString();
                        labelJLM = dataGridView3.Rows[indexPosition].Cells["JLM"].Value.ToString();
                        labelTa1 = dataGridView3.Rows[indexPosition].Cells["Technische_Ausprägung_1"].Value.ToString();
                        labelTa2 = dataGridView3.Rows[indexPosition].Cells["Technische_Ausprägung_2"].Value.ToString();
                        labelTa3 = dataGridView3.Rows[indexPosition].Cells["Technische_Ausprägung_3"].Value.ToString();

                        label = new PrintDocument();
                        PaperSize pS = new PaperSize("Custom Size", 620, 350);
                        label.DefaultPageSettings.PaperSize = pS;
                        label.PrinterSettings.PrinterName = comboBox3.Text;
                        label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                        label.PrintPage += new PrintPageEventHandler(label_PrintPage);

                        if (print && comboBox3.Text != "")
                        {
                            label.Print();
                            label.Print();
                        }

                        // Log schreiben
                        dataGridView4.Rows.Add();
                        dataGridView4.Rows[dataGridView4.RowCount-1].Cells["Time"].Value = DateTime.Now.ToShortTimeString();
                        dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Event"].Value = "Serial " + textBox1.Text + " booked to " + labelManufacturer.ToString() + " - " + labelModel.ToString() +" - " + labelPosition.ToString();
                        textBox1.Text = "";

                        // Druckstrings sicherheitshalber wieder zurück setzen
                        labelSerialNumber = "";
                        labelManufacturer = "";
                        labelModel = "";
                        labelPosition = "";
                        labelVenue = "";
                        labelJLM = "";
                        labelTa1 = "";
                        labelTa2 = "";
                        labelTa3 = "";
                    }

                    
                    // Liste der vorhandenen Seriennummern updaten, damit sie nicht neu vergeben werden kann
                    updateListeSerialPositionen();

                }
                #endregion vorhanden
                // Gibt es die Seriennummer nicht ?
                #region neu
                else 
                {
                    dataGridView4.Rows.Add();
                    dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Time"].Value = DateTime.Now.ToShortTimeString();
                    dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Event"].Value = "Serial " + textBox1.Text + " was not found in this Venue ";
                    textBox1.Text = "";
                }
                #endregion neu
            }
        }
        public void updateListeSerialPositionen()
        {
            // Liste der vorhandenen Seriennummern updaten, damit sie nicht neu vergeben werden kann

            listeSerialPositionen.RemoveRange(0, listeSerialPositionen.Count);
            for (int i = 0; i < dataGridView3.RowCount; i++)
            {
                listeSerialPositionen.Add(dataGridView3.Rows[i].Cells["Seriennummer"].Value.ToString());
            }
        }
        #endregion

        #region ChangeVenue
        //
        // Venue wechselt
        //
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (helper.getTable3() != null) helper.getTable3().DefaultView.RowFilter = string.Format("Venue LIKE '{0}'", (Login.setFilterCharacters(comboBox1.Text)+"*"));

            updateListeSerialPositionen();

            textBox1.Focus();
        }
        #endregion

        #region Export
        //
        // Venueliste zu Excel ausgeben
        //
        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView3.SelectAll();
            DataObject dataObj = dataGridView3.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView3.ClearSelection();
        }

        //
        // Seriennummern zu Excel ausgeben
        //
        private void button5_Click(object sender, EventArgs e)
        {

            dataGridView1.SelectAll();
            DataObject dataObj = dataGridView1.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView1.ClearSelection();
        }

        //
        // Log zu Excel ausgeben
        //
        private void button7_Click(object sender, EventArgs e)
        {
            dataGridView4.SelectAll();
            DataObject dataObj = dataGridView4.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView4.ClearSelection();
        }

        //
        // Bulk zu Excel ausgeben
        //
        private void button6_Click(object sender, EventArgs e)
        {
            dataGridView2.SelectAll();
            DataObject dataObj = dataGridView2.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView2.ClearSelection();
        }
        #endregion

        #region Booking
        private void button9_Click(object sender, EventArgs e)
        {
            if (booking)
            {
                button9.Text = "Booking Off";
                button9.BackColor = Color.Red;
                booking = !booking;
            }
            else
            {
                button9.Text = "Booking On";
                button9.BackColor = Color.Green;
                booking = !booking;
            }
        }
        #endregion

        #region Packstücknummer
        //
        // Packstücknummer -1
        //
        private void button10_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(textBox3.Text) > 0)
            {
                textBox3.Text = (Convert.ToInt32(textBox3.Text) - 1).ToString();
            }
        }

        //
        // Packstücknummer +1
        //
        private void button11_Click(object sender, EventArgs e)
        {
            int n;
            bool isNumericButton12 = int.TryParse(button12.Text, out n);
            bool isNumericTextBox3 = int.TryParse(textBox3.Text, out n);

            if (isNumericButton12 && isNumericTextBox3)
            {
                if (Convert.ToInt32(button12.Text) > Convert.ToInt32(textBox3.Text))
                {
                    textBox3.Text = (Convert.ToInt32(textBox3.Text) + 1).ToString();
                }
            }
            else
            {
                MessageBox.Show("Bitte nur Zahlen als Package Number verwenden.", "Fehler");
            }
        }

        //
        // Packstücknummer erhöhen
        //
        private void button8_Click(object sender, EventArgs e)
        {
            // um eins erhöhen und in die DB schreiben
            sql.sendSQL("UPDATE tbl_systemData SET letztesPackstueck = letztesPackstueck + 1");

            // und wieder zurücklesen aus DB
            String[,] neuePackstückNr = sql.receiveSQL("SELECT letztesPackstueck FROM tbl_systemData");
            textBox3.Text = neuePackstückNr[0, 0];

            // und Packzettel für Palette ausdrucken
            palettenzettel = new PrintDocument();
            PaperSize pS = new PaperSize();
            pS.RawKind = (int)PaperKind.A4Rotated;
            palettenzettel.DefaultPageSettings.PaperSize = pS;
            palettenzettel.PrinterSettings.PrinterName = comboBox4.Text;
            palettenzettel.PrinterSettings.DefaultPageSettings.PaperSize = pS;
            palettenzettel.PrintPage += new PrintPageEventHandler(palettenzettel_PrintPage);

            if (print && comboBox4.Text != "")
            {
                palettenzettel.Print();
                palettenzettel.Print();
            }

        }
        #endregion

        #region Drucken
        //
        // Drucken ein und ausschalten
        //
        private void button3_Click(object sender, EventArgs e)
        {


            if (print)
            {
                button3.Text = "Printing Off";
                button3.BackColor = Color.Red;
                print = !print;
            }
            else
            {
                button3.Text = "Printing On";
                button3.BackColor = Color.Green;
                print = !print;
            }
        }

        private void button13_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView3.SelectedRows.Count == 1)
                {
                    indexPosition = dataGridView3.SelectedRows[0].Index;
                    // Zugehöriges Label ausdrucken
                    labelSerialNumber = dataGridView3.Rows[indexPosition].Cells["Seriennummer"].Value.ToString();
                    labelManufacturer = dataGridView3.Rows[indexPosition].Cells["Manufacturer"].Value.ToString();
                    labelModel = dataGridView3.Rows[indexPosition].Cells["Model"].Value.ToString();
                    labelPosition = dataGridView3.Rows[indexPosition].Cells["Positions_ID"].Value.ToString();
                    labelVenue = dataGridView3.Rows[indexPosition].Cells["Venue"].Value.ToString();
                    labelJLM = dataGridView3.Rows[indexPosition].Cells["JLM"].Value.ToString();
                    labelTa1 = dataGridView3.Rows[indexPosition].Cells["Technische_Ausprägung_1"].Value.ToString();
                    labelTa2 = dataGridView3.Rows[indexPosition].Cells["Technische_Ausprägung_2"].Value.ToString();
                    labelTa3 = dataGridView3.Rows[indexPosition].Cells["Technische_Ausprägung_3"].Value.ToString();
                    labelFittingNr = dataGridView3.Rows[indexPosition].Cells["Fitting-No"].Value.ToString();

                    label = new PrintDocument();

                    if (comboBox3.Text != "TEC B-EV4-T" && comboBox3.Text != "TEC B-EV4-G")
                    {
                        PaperSize pS = new PaperSize("Custom Size", 620, 350);
                        label.DefaultPageSettings.PaperSize = pS;
                        label.PrinterSettings.PrinterName = comboBox3.Text;
                        label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                        label.PrintPage += new PrintPageEventHandler(label_PrintPage);
                    }
                    else
                    {
                        //Labeldrucker mit Silber-Labels
                        label.PrinterSettings.PrinterName = comboBox3.Text;
                        label.PrintPage += new PrintPageEventHandler(label_PrintPage);
                    }

                    if (comboBox3.Text != "")
                    {
                        label.Print();
                    }

                    // Log schreiben
                    dataGridView4.Rows.Add();
                    dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Time"].Value = DateTime.Now.ToShortTimeString();
                    dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Event"].Value = " Label for Serial " + textBox1.Text + " printed again ";
                    textBox1.Text = "";
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Fehler in button3_Click:\r\n\r\nFehlermeldung:\r\n" + ex.StackTrace.ToString());
            }
        }

        private void button14_Click(object sender, EventArgs e)
        {
            // und Packzettel für Palette ausdrucken
            palettenzettel = new PrintDocument();
            PaperSize pS = new PaperSize();
            pS.RawKind = (int)PaperKind.A4Rotated;
            palettenzettel.DefaultPageSettings.PaperSize = pS;
            palettenzettel.PrinterSettings.PrinterName = comboBox4.Text;
            palettenzettel.PrinterSettings.DefaultPageSettings.PaperSize = pS;
            palettenzettel.PrintPage += new PrintPageEventHandler(palettenzettel_PrintPage);

            if (comboBox4.Text != "")
            {
                palettenzettel.Print();
            }
        }

        //
        // Eventhandler für Ausdruck Palettenzettel
        //
        private void palettenzettel_PrintPage(object sender, PrintPageEventArgs e)
        {

            SolidBrush brush = new SolidBrush(Color.Black);
            System.Drawing.Font header = new System.Drawing.Font(FontFamily.GenericSansSerif, 40.0F, FontStyle.Bold);

            String shipName = "";
            if (Login.currentDBName == "Quantum") shipName = "S697 - Quantum of the Seas";
            else if (Login.currentDBName == "Hyperion") shipName = "2300 Aida Hyperion";
            else if (Login.currentDBName == "Anthem") shipName = "S698 - Anthem of the Seas";

            e.Graphics.DrawString(shipName, header, brush, 50, 50);
            e.Graphics.DrawString("Venue: " + comboBox1.Text, header, brush, 50, 200);
            e.Graphics.DrawString("Package No.: " + textBox3.Text, header, brush, 50, 350);
            e.Graphics.DrawString("Date: " + DateTime.Now.ToString(), header, brush, 50, 500);

            // Logo
            e.Graphics.DrawImage(Worktool.Properties.Resources.ASC_Logo_quadratisch, 600, 600, 200, 200);
        }

        //
        // Print Eventhandler
        //
        private void label_PrintPage(object sender, PrintPageEventArgs e)
        {
            try
            {
                String schiff_huellenNr = "";
                if (Login.currentDBName == "Hyperion")
                {
                    String[,] temp = sql.receiveSQL("SELECT [Schiff_HuellenNr] FROM [tbl_systemData] WHERE ID = 1");
                    if (temp.GetLength(1) > 0) schiff_huellenNr = temp[0, 0];
                }

                if (comboBox3.Text != "TEC B-EV4-T" && comboBox3.Text != "TEC B-EV4-G")
                {
                    SolidBrush brush = new SolidBrush(Color.Black);
                    System.Drawing.Font header = new System.Drawing.Font(FontFamily.GenericSansSerif, 8.0F, FontStyle.Bold);
                    Code128BarcodeDraw barcode128 = BarcodeDrawFactory.Code128WithChecksum;
                    Image img;

                    e.Graphics.DrawString("Venue: " + labelVenue, header, brush, 5, 5);
                    e.Graphics.DrawString("Manufacturer: " + labelManufacturer, header, brush, 5, 17);
                    e.Graphics.DrawString("Model: " + labelModel, header, brush, 5, 29);
                    e.Graphics.DrawString("SN: " + labelSerialNumber, header, brush, 5, 41);
                    e.Graphics.DrawString("JLM: " + labelJLM, header, brush, 5, 53);
                    e.Graphics.DrawString("Position: " + labelPosition, header, brush, 5, 65);
                    e.Graphics.DrawString(labelTa1, header, brush, 5, 77);
                    e.Graphics.DrawString(labelTa2, header, brush, 5, 89);
                    e.Graphics.DrawString(labelTa3, header, brush, 5, 101);
                    if (Login.currentDBName == "Hyperion") e.Graphics.DrawString("Fitting-No: "+labelFittingNr, header, brush, 5, 113);
                    if (Login.currentDBName == "Hyperion" && schiff_huellenNr != "") e.Graphics.DrawString("Hüllennummer: "+schiff_huellenNr, header, brush, 5, 125);

                    e.Graphics.DrawImage(Worktool.Properties.Resources.ASC_Logo_quadratisch, 200, 10, 30, 30);
                    if (labelSerialNumber != null && labelSerialNumber != "")
                    {
                        img = barcode128.Draw(labelSerialNumber, 30);
                        e.Graphics.DrawImage(img, 5, 113);

                    }
                }
                else
                {
                    //Labeldrucker mit Silber-Labels
                    SolidBrush brush = new SolidBrush(Color.Black);
                    System.Drawing.Font header = new System.Drawing.Font(FontFamily.GenericSansSerif, 7.0F, FontStyle.Bold);
                    Code128BarcodeDraw barcode128 = BarcodeDrawFactory.Code128WithChecksum;
                    Image img;

                    e.Graphics.DrawString("Venue: " + labelVenue, header, brush, 5, 5);
                    e.Graphics.DrawString("Manufacturer: " + labelManufacturer, header, brush, 5, 17);
                    e.Graphics.DrawString("Model: " + labelModel, header, brush, 5, 29);
                    e.Graphics.DrawString("SN: " + labelSerialNumber, header, brush, 5, 41);
                    e.Graphics.DrawString("JLM: " + labelJLM, header, brush, 5, 53);
                    e.Graphics.DrawString("Position: " + labelPosition, header, brush, 5, 65);
                    e.Graphics.DrawString(labelTa1, header, brush, 5, 77);
                    e.Graphics.DrawString(labelTa2, header, brush, 5, 89);
                    e.Graphics.DrawString(labelTa3, header, brush, 5, 101);
                    if (Login.currentDBName == "Hyperion") e.Graphics.DrawString("Fitting-No: " + labelFittingNr, header, brush, 5, 113);
                    if (Login.currentDBName == "Hyperion" && schiff_huellenNr != "") e.Graphics.DrawString("Hüllennummer: " + schiff_huellenNr, header, brush, 5, 125);

                    e.Graphics.DrawImage(Worktool.Properties.Resources.ASC_Logo_quadratisch, 250, 0, 40, 40);
                    if (labelSerialNumber != null && labelSerialNumber != "")
                    {
                        img = barcode128.Draw(labelSerialNumber, 40);
                        e.Graphics.DrawImage(img, 6, 148);
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Fehler in label_PrintPage:\r\n\r\nFehlermeldung:\r\n" + ex.StackTrace.ToString());
            }
        }
        #endregion

        #region Daten neu laden
        private void button15_Click(object sender, EventArgs e)
        {
            reloadAllData();
        }

        public void reloadAllData()
        {
            Cursor.Current = Cursors.WaitCursor;
            this.Enabled = false;
            String selectedVenue = comboBox1.Text;
            fillTablesInit();
            fillElementsInit();
            initFilterSettings();
            comboBox1.Text = selectedVenue;
            this.Enabled = true;
            Cursor.Current = Cursors.Default;
        }
        #endregion

    }
}
